package xyz.codej.websocket.netty.server.handler;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @ClassName: HeartbeatHandler
 * @Description 心跳处理
 * @Author 王华君
 * @Date 2020/4/6 11:52 上午
 * @VERSION 1.0
 */
@Slf4j
@Component
@ChannelHandler.Sharable
public class HeartbeatHandler extends ChannelInboundHandlerAdapter {
    private static final ByteBuf HEARTBEAT_SEQUENCE = Unpooled.unreleasableBuffer(
            Unpooled.copiedBuffer("Heartbeat", CharsetUtil.UTF_8));

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            String type = "";
            if (event.state() == IdleState.READER_IDLE) {
                type = "read idle";
            } else if (event.state() == IdleState.WRITER_IDLE) {
                type = "write idle";
            } else if (event.state() == IdleState.ALL_IDLE) {
                type = "all idle";
            }

            // 心跳发送到远端
            // 发送的心跳并添加一个侦听器，如果发送操作失败将关闭连接
            ctx.channel()
                    // 如果是向客户端发送文本消息，则需要发送 TextWebSocketFrame 消息
                    .writeAndFlush(new TextWebSocketFrame("HeartBeat At " + new java.util.Date().toString()))
                    .addListener(ChannelFutureListener.CLOSE_ON_FAILURE);

//            log.info(ctx.channel().remoteAddress() + "超时类型：" + type);
        } else {
            // 事件不是一个 IdleStateEvent 的话，就将它传递给下一个处理程序
            super.userEventTriggered(ctx, evt);
        }
    }
}
